/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package IO;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import IO.Environment;

/**
 *
 * @author Alex
 */
public class IO {

    //Lấy toàn bộ nội dung file
    public static String getFileContents(String fileName) throws java.io.IOException
     {
        StringBuilder contents = new StringBuilder();
        String line = new String();
	try
        {
		FileReader fileReader = new FileReader(fileName);
		BufferedReader in = new BufferedReader(fileReader);
                String lsp = Environment.getLineSeparator();
		while ((line = in.readLine()) != null)
                {
			contents.append(line + lsp); 
		}
	}
        catch (FileNotFoundException fnfe)
        {
		System.err.println("The file \"" + fileName + "\" could not be found.");
		return null;
	}
	return contents.toString();
    }
        /**
     * Đọc file
     * @param fileName đường dẫn đọc file
     * @return chuỗi byte đọc được
     */
    public static byte[] ReadFile(String fileName)
    {

        byte[] kq = null;
        try
        {
            FileInputStream fi = new FileInputStream(fileName);
            //kq = new byte[fi.available()];
            int ch = 0;

            while((ch = fi.read()) != -1)
            {

            }
            fi.close();
        }
        catch (FileNotFoundException ex1)
        {
            System.out.println("File" + fileName + " not found!");
        }
        catch (Exception ex2)
        {
            System.out.println("Can not read file" + fileName);
        }
        return kq;
    }

    /**
     * Ghi xuống file
     * @param fileName đường dẫn đọc file
     * @param str chuỗi cần ghi
     * @throws IOException
     */
     public static void writeToFile(String fileName,String str) throws IOException
    {

        byte[] kq = null;
        //FileOutputStream fo;
        FileWriter fw = null;
        
        try
        {
           fw = new FileWriter(fileName,false);
           fw.write(str);
          // fo = new FileOutputStream(fileName,false);
           //fo.write(str.getBytes());
           
        }
        catch (FileNotFoundException ex1)
        {
            System.err.println("File" + fileName + " not found!");
        }
        
        catch (Exception ex2)
        {
           System.err.println("Can not read file" + fileName);
        }
        finally
        {
            try
            {
                //fo.flush();
                //fo.close();
                fw.flush();
                fw.close();
            }
            catch (IOException ex)
            {
                Logger.getLogger(IO.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }



     private static final String errMsg = "Error attempting to launch web browser";
     /**
      * Mở trình duyệt mặc định của hệ thống với url được truyền vào
      * @param url đối tượng String
      */
    public static void openURL(String url)
    {
        String osName = System.getProperty("os.name");
        try
        {
            if (osName.startsWith("Mac OS"))
            {
                Class fileMgr = Class.forName("com.apple.eio.FileManager");
                @SuppressWarnings("unchecked")
                Method openURL = fileMgr.getDeclaredMethod("openURL",
                                                           new Class[]
                        {
                            String.class
                        });
                openURL.invoke(null, new Object[]
                        {
                            url
                        });
            }
            else if (osName.startsWith("Windows"))
            {
                Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
            }
            else
            { //assume Unix or Linux
                String[] browsers =
                {
                    "firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape"
                };
                String browser = null;
                for (int count = 0; count < browsers.length && browser == null; count++)
                {
                    if (Runtime.getRuntime().exec(
                            new String[]
                            {
                                "which", browsers[count]
                            }).waitFor() == 0)
                    {
                        browser = browsers[count];
                    }
                }
                if (browser == null)
                {
                    throw new Exception("Could not find web browser");
                }
                else
                {
                    Runtime.getRuntime().exec(new String[]
                            {
                                browser, url
                            });
                }
            }
        }
        catch (Exception e)
        {
            JOptionPane.showMessageDialog(null, errMsg + ":\n" + e.getLocalizedMessage());
        }
    }

    private IO()
    {
    }
}
